class BookmarkManager {
  constructor() {
    this.bookmarks = [];
    this.filteredBookmarks = [];
    this.allTags = new Set();
    this.activeTags = new Set();
    this.currentTheme = 'light';
    this.tagsExpanded = false;
    this.init();
  }

  async init() {
    await this.loadSettings();
    await this.loadBookmarks();
    this.bindEvents();
    this.updateStats();
    this.generateTags();
    this.renderTagFilters();
  }

  bindEvents() {
    const syncBtn = document.getElementById('syncBtn');
    const searchInput = document.getElementById('searchInput');
    const clearSearch = document.getElementById('clearSearch');
    const themeBtn = document.getElementById('themeBtn');
    const exportBtn = document.getElementById('exportBtn');
    const tagToggleBtn = document.getElementById('tagToggleBtn');

    syncBtn.addEventListener('click', () => this.syncBookmarks());
    searchInput.addEventListener('input', (e) => this.searchBookmarks(e.target.value));
    clearSearch.addEventListener('click', () => this.clearSearch());
    themeBtn.addEventListener('click', () => this.toggleTheme());
    exportBtn.addEventListener('click', () => this.exportBookmarks());
    tagToggleBtn.addEventListener('click', () => this.toggleTagsExpansion());
  }

  async loadSettings() {
    try {
      const result = await chrome.storage.local.get(['theme']);
      this.currentTheme = result.theme || 'light';
      this.applyTheme();
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  }

  toggleTheme() {
    this.currentTheme = this.currentTheme === 'light' ? 'dark' : 'light';
    this.applyTheme();
    chrome.storage.local.set({ theme: this.currentTheme });
  }

  applyTheme() {
    document.body.className = this.currentTheme === 'dark' ? 'dark-theme' : '';
    const themeBtn = document.getElementById('themeBtn');
    themeBtn.textContent = this.currentTheme === 'dark' ? '☀️' : '🌙';
  }

  async syncBookmarks() {
    const syncBtn = document.getElementById('syncBtn');
    const loading = document.getElementById('loading');
    const bookmarkList = document.getElementById('bookmarkList');

    try {
      // 显示加载状态
      syncBtn.classList.add('syncing');
      syncBtn.disabled = true;
      loading.style.display = 'block';
      bookmarkList.style.display = 'none';

      // 获取所有书签
      const bookmarkTree = await chrome.bookmarks.getTree();
      const allBookmarks = this.flattenBookmarks(bookmarkTree);

      // 保存到本地存储
      await chrome.storage.local.set({
        bookmarks: allBookmarks,
        lastSync: new Date().toISOString()
      });

      this.bookmarks = allBookmarks;
      this.filteredBookmarks = [...allBookmarks];
      
      // 重新生成标签和过滤器
      this.generateTags();
      this.renderTagFilters();
      
      // 更新界面
      this.renderBookmarks();
      this.updateStats();
      
      // 显示成功消息
      this.showMessage('同步成功！', 'success');

    } catch (error) {
      console.error('同步失败:', error);
      this.showMessage('同步失败，请重试', 'error');
    } finally {
      // 恢复按钮状态
      syncBtn.classList.remove('syncing');
      syncBtn.disabled = false;
      loading.style.display = 'none';
      bookmarkList.style.display = 'block';
    }
  }

  flattenBookmarks(bookmarkTree, parentPath = '') {
    let result = [];
    
    for (const node of bookmarkTree) {
      if (node.children) {
        // 这是一个文件夹
        const currentPath = parentPath ? `${parentPath}/${node.title}` : node.title;
        result = result.concat(this.flattenBookmarks(node.children, currentPath));
      } else if (node.url) {
        // 这是一个书签
        const tags = this.extractTags(node.title, node.url, parentPath);
        result.push({
          id: node.id,
          title: node.title,
          url: node.url,
          folder: parentPath || '根目录',
          dateAdded: node.dateAdded,
          tags: tags
        });
      }
    }
    
    return result;
  }

  extractTags(title, url, folder) {
    const tags = new Set();
    
    // 从文件夹名提取标签
    if (folder && folder !== '根目录') {
      folder.split('/').forEach(part => {
        if (part.trim()) tags.add(part.trim());
      });
    }
    
    // 从URL域名提取标签
    try {
      const domain = new URL(url).hostname.replace('www.', '');
      const domainParts = domain.split('.');
      if (domainParts.length > 1) {
        tags.add(domainParts[0]);
      }
    } catch (e) {}
    
    // 从标题提取常见关键词
    const commonKeywords = ['github', 'docs', 'api', 'tutorial', 'guide', 'blog', 'news', 'tool', 'dev', 'design'];
    const titleLower = title.toLowerCase();
    commonKeywords.forEach(keyword => {
      if (titleLower.includes(keyword)) {
        tags.add(keyword);
      }
    });
    
    return Array.from(tags).slice(0, 5); // 限制标签数量
  }

  generateTags() {
    this.allTags.clear();
    this.bookmarks.forEach(bookmark => {
      if (bookmark.tags) {
        bookmark.tags.forEach(tag => this.allTags.add(tag));
      }
    });
  }

  renderTagFilters() {
    const tagFilters = document.getElementById('tagFilters');
    const tagToggleBtn = document.getElementById('tagToggleBtn');
    if (!tagFilters) return;
    
    const sortedTags = Array.from(this.allTags).sort();
    
    tagFilters.innerHTML = sortedTags.map(tag => 
      `<span class="tag-filter" data-tag="${tag}">${tag}</span>`
    ).join('');
    
    // 显示/隐藏展开按钮
    if (sortedTags.length > 8) {  // 如果标签超过8个，显示展开按钮
      tagToggleBtn.style.display = 'flex';
      tagFilters.classList.add('collapsed');
      this.tagsExpanded = false;
      this.updateToggleButton();
    } else {
      tagToggleBtn.style.display = 'none';
      tagFilters.classList.remove('collapsed');
    }
    
    // 绑定标签点击事件
    tagFilters.querySelectorAll('.tag-filter').forEach(tagEl => {
      tagEl.addEventListener('click', () => {
        const tag = tagEl.dataset.tag;
        this.toggleTagFilter(tag, tagEl);
      });
    });
  }

  toggleTagsExpansion() {
    const tagFilters = document.getElementById('tagFilters');
    const tagToggleBtn = document.getElementById('tagToggleBtn');
    
    this.tagsExpanded = !this.tagsExpanded;
    
    if (this.tagsExpanded) {
      tagFilters.classList.remove('collapsed');
      tagFilters.classList.add('expanded');
    } else {
      tagFilters.classList.add('collapsed');
      tagFilters.classList.remove('expanded');
    }
    
    this.updateToggleButton();
  }

  updateToggleButton() {
    const tagToggleBtn = document.getElementById('tagToggleBtn');
    const toggleText = tagToggleBtn.querySelector('.toggle-text');
    
    if (this.tagsExpanded) {
      toggleText.textContent = '收起标签';
      tagToggleBtn.classList.add('expanded');
    } else {
      toggleText.textContent = '展开更多';
      tagToggleBtn.classList.remove('expanded'); 
    }
  }

  toggleTagFilter(tag, element) {
    if (this.activeTags.has(tag)) {
      this.activeTags.delete(tag);
      element.classList.remove('active');
    } else {
      this.activeTags.add(tag);
      element.classList.add('active');
    }
    this.applyFilters();
  }

  applyFilters() {
    let filtered = [...this.bookmarks];
    
    // 应用标签过滤
    if (this.activeTags.size > 0) {
      filtered = filtered.filter(bookmark => 
        bookmark.tags && bookmark.tags.some(tag => this.activeTags.has(tag))
      );
    }
    
    // 应用搜索过滤
    const searchInput = document.getElementById('searchInput');
    if (searchInput && searchInput.value.trim()) {
      const searchTerm = searchInput.value.toLowerCase();
      filtered = filtered.filter(bookmark => 
        bookmark.title.toLowerCase().includes(searchTerm) ||
        bookmark.url.toLowerCase().includes(searchTerm) ||
        bookmark.folder.toLowerCase().includes(searchTerm)
      );
    }
    
    this.filteredBookmarks = filtered;
    this.renderBookmarks(searchInput ? searchInput.value : '');
    this.updateFilteredCount();
  }

  updateFilteredCount() {
    const filteredCount = document.getElementById('filteredCount');
    if (filteredCount) {
      if (this.activeTags.size > 0 || (document.getElementById('searchInput') && document.getElementById('searchInput').value.trim())) {
        filteredCount.textContent = `筛选后 ${this.filteredBookmarks.length} 个`;
        filteredCount.style.display = 'inline';
      } else {
        filteredCount.style.display = 'none';
      }
    }
  }

  async loadBookmarks() {
    try {
      const result = await chrome.storage.local.get(['bookmarks', 'lastSync']);
      this.bookmarks = result.bookmarks || [];
      this.filteredBookmarks = [...this.bookmarks];
      this.renderBookmarks();
    } catch (error) {
      console.error('加载书签失败:', error);
    }
  }

  searchBookmarks(query) {
    this.applyFilters();
  }

  clearSearch() {
    const searchInput = document.getElementById('searchInput');
    searchInput.value = '';
    this.applyFilters();
  }

  clearAllFilters() {
    // 清除搜索
    const searchInput = document.getElementById('searchInput');
    if (searchInput) searchInput.value = '';
    
    // 清除标签过滤
    this.activeTags.clear();
    document.querySelectorAll('.tag-filter.active').forEach(el => {
      el.classList.remove('active');
    });
    
    this.applyFilters();
  }

  async exportBookmarks() {
    try {
      const data = {
        exportDate: new Date().toISOString(),
        totalBookmarks: this.bookmarks.length,
        bookmarks: this.bookmarks.map(bookmark => ({
          title: bookmark.title,
          url: bookmark.url,
          folder: bookmark.folder,
          tags: bookmark.tags || [],
          dateAdded: bookmark.dateAdded
        }))
      };
      
      const jsonString = JSON.stringify(data, null, 2);
      const blob = new Blob([jsonString], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      
      const filename = `LinkHunter_bookmarks_${new Date().toISOString().split('T')[0]}.json`;
      
      // 使用Chrome下载API
      await chrome.downloads.download({
        url: url,
        filename: filename,
        saveAs: true
      });
      
      this.showMessage('导出成功！', 'success');
      
      // 清理URL对象
      setTimeout(() => URL.revokeObjectURL(url), 1000);
      
    } catch (error) {
      console.error('导出失败:', error);
      this.showMessage('导出失败，请重试', 'error');
    }
  }

  renderBookmarks(searchQuery = '') {
    const bookmarkList = document.getElementById('bookmarkList');
    
    if (this.filteredBookmarks.length === 0) {
      if (this.bookmarks.length === 0) {
        bookmarkList.innerHTML = `
          <div class="empty-state">
            <div class="empty-icon">📖</div>
            <p>还没有收藏夹数据</p>
            <p class="empty-hint">点击上方"同步收藏夹"按钮开始</p>
          </div>
        `;
      } else {
        bookmarkList.innerHTML = `
          <div class="empty-state">
            <div class="empty-icon">🔍</div>
            <p>没有找到匹配的收藏</p>
            <p class="empty-hint">试试其他关键词</p>
          </div>
        `;
      }
      return;
    }

    const bookmarkItems = this.filteredBookmarks.map(bookmark => {
      const favicon = this.getFaviconUrl(bookmark.url);
      const highlightedTitle = this.highlightText(bookmark.title, searchQuery);
      const highlightedUrl = this.highlightText(bookmark.url, searchQuery);
      
      return `
        <div class="bookmark-item" data-url="${bookmark.url}">
          <img class="bookmark-favicon" src="${favicon}" alt="">
          <div class="bookmark-info">
            <div class="bookmark-title">${highlightedTitle}</div>
            <div class="bookmark-url">${highlightedUrl}</div>
          </div>
        </div>
      `;
    }).join('');

    bookmarkList.innerHTML = bookmarkItems;

    // 绑定点击事件
    bookmarkList.querySelectorAll('.bookmark-item').forEach(item => {
      item.addEventListener('click', () => {
        const url = item.dataset.url;
        chrome.tabs.create({ url });
        window.close();
      });
    });

    // 绑定图片错误事件
    bookmarkList.querySelectorAll('.bookmark-favicon').forEach(img => {
      img.addEventListener('error', () => {
        img.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><text y="18" font-size="20">🔗</text></svg>';
      });
    });
  }

  getFaviconUrl(url) {
    try {
      const domain = new URL(url).hostname;
      return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`;
    } catch {
      return 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><text y="18" font-size="20">🔗</text></svg>';
    }
  }

  highlightText(text, query) {
    if (!query.trim()) return text;
    
    const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
    return text.replace(regex, '<span class="highlight">$1</span>');
  }

  async updateStats() {
    const bookmarkCount = document.getElementById('bookmarkCount');
    const lastSync = document.getElementById('lastSync');
    
    bookmarkCount.textContent = `共 ${this.bookmarks.length} 个收藏`;
    
    try {
      const result = await chrome.storage.local.get('lastSync');
      if (result.lastSync) {
        const syncDate = new Date(result.lastSync);
        const now = new Date();
        const diffMinutes = Math.floor((now - syncDate) / (1000 * 60));
        
        if (diffMinutes < 1) {
          lastSync.textContent = '刚刚同步';
        } else if (diffMinutes < 60) {
          lastSync.textContent = `${diffMinutes}分钟前同步`;
        } else if (diffMinutes < 1440) {
          const hours = Math.floor(diffMinutes / 60);
          lastSync.textContent = `${hours}小时前同步`;
        } else {
          const days = Math.floor(diffMinutes / 1440);
          lastSync.textContent = `${days}天前同步`;
        }
      } else {
        lastSync.textContent = '未同步';
      }
    } catch (error) {
      lastSync.textContent = '未同步';
    }
  }

  showMessage(message, type = 'info') {
    // 创建消息提示
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.textContent = message;
    messageDiv.style.cssText = `
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      background: ${type === 'success' ? '#4CAF50' : '#f44336'};
      color: white;
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 12px;
      z-index: 1000;
      animation: slideDown 0.3s ease;
    `;
    
    document.body.appendChild(messageDiv);
    
    setTimeout(() => {
      messageDiv.remove();
    }, 2000);
  }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
  new BookmarkManager();
});

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateX(-50%) translateY(-20px);
    }
    to {
      opacity: 1;
      transform: translateX(-50%) translateY(0);
    }
  }
`;
document.head.appendChild(style);